<template>
<div class="content">
  <!-- <audio ref="audioRefPlay" :src="audioSrc" preload="auto"></audio> -->
  <audio ref="audioRefPlay" controls style="opacity: 0;" preload="auto">
    <source :src="audioSrc" type="audio/mp3">
    Your browser does not support the audio element.
  </audio>
  <button @click="play" style="opacity: 0;">播放</button>
  <div class="usernameBox fade-in">
    <van-field placeholder="请输入账号" v-model="param.username" :border="false" left-icon="user" label="" clearable style="color: #00FFFF;" />
    <div class="line"></div>
  </div>
  <div class="passwordBox fade-in">
    <van-field placeholder="请输入密码" v-model="param.password" :border="false" type="password" left-icon="diamond" label="" clearable style="color: #00FFFF;" />
    <div class="line"></div>
  </div>
  <div class="captchaBox fade-in">
    <div>
      <van-field placeholder="请输入验证码" v-model="param.weiCode" :border="false" left-icon="comment" type="number" maxlength="4" label="" clearable @keyup.enter="submitForm()" style="color: #00FFFF;" />
      <div class="line"></div>
    </div>
    <div style="width: 10px;height: 100%;"></div>
    <canvas id="captchaCanvas"></canvas>
  </div>
  <van-button class="login-btn fade-in" v-if="showBtn" @click="submitForm()">
      登&nbsp;&nbsp;录
  </van-button>
</div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { showToast, showFailToast, showDialog } from 'vant'
import { isMobile, sourceHeader } from '@/utils/plugins'
import useSettingStore from '@/store/modules/setting'
const settings = useSettingStore()

const route = useRoute()
const router = useRouter()

let weiCode = ''
const token = ref<string>('eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJyZWFsTmFtZSI6IjcxNDExOTM4IiwicGFzc3dvcmQiOiIyMzhjOWEwYmU0YWE0NzY4OWNkODA3MmJjOWJiYzdmZiIsImFjY291bnQiOiI3MTQxMTkzOCJ9.mf7TaIJr15r4U1slfE_lsROQypIJaopZdZC0PdM0kuY')

const audioSrc = ref<any>(null)
const audioRefPlay = ref<any>(null)

interface LoginInfo {
    username: string
    password: string
    weiCode: string
}

const param = reactive<LoginInfo>({
    username: 'admin',
    password: 'admin',
    weiCode: ''
})

const showBtn = ref<boolean>(false)

watch([() => param.username, () => param.password, () => param.weiCode, ], (newVal) => {
  console.log(newVal)
  newVal.forEach((item) => {
    if (item != '') {
      showBtn.value = true
    }
  })
})

const play = () => {
  if (audioRefPlay.value) {
    // audioSrc.value = 'http://123.57.3.138/image/Cornfield Chase.mp3'
    // audioSrc.value = 'http://101.200.90.7/image/Cornfield Chase.mp3'
    // audioSrc.value = 'https://www.paperfrogwei.com/image/Cornfield Chase.mp3'
    audioSrc.value = sourceHeader() + '/image/Cornfield Chase.mp3'
    if (audioSrc.value) {
      audioRefPlay.value.play().catch(error => {
        console.error('Error playing audio:', error);
        pause()
        return
      })
    } else {
      return
    } 
  }
}

const pause = () => {
  audioRefPlay.value.pause()
}

const submitForm = () => {
    if (
        param.weiCode.toLowerCase() != weiCode.toLowerCase() ||
        param.weiCode.toUpperCase() != weiCode.toUpperCase()
    ) {
        param.weiCode = ''
        // generateCaptcha()
        generateSingleDigitCaptcha()
        showToast('验证码不正确')
        return
    }
    if (param.username == '') {
      showFailToast('请输入账号!')
      return
    }
    if (param.password == '') {
      showFailToast('请输入密码!')
      return
    }
    settings.handlerLoadingShow(true)
    if (param.username == 'admin' && param.password == 'admin') {
        sessionStorage.setItem('token', token.value)
        settings.handlerSetIsLogin(true)
        settings.handlerLoadingShow(false)
        // router.push('/me')
        router.push('/menu')
    } else {
        settings.handlerLoadingShow(false)
        showFailToast('账号/密码错误，请重新输入!')
        param.username = ''
        param.password = ''
        param.weiCode = ''
        // generateCaptcha()
        generateSingleDigitCaptcha()
    }
}

// 随机字母验证码
function generateCaptcha() {
  const canvas = document.getElementById('captchaCanvas') as HTMLCanvasElement
  const context = canvas.getContext('2d') as CanvasRenderingContext2D

  // Set canvas dimensions
  canvas.width = 100
  canvas.height = 50

  // Generate random code
  let code = ''
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
  for (let i = 0; i < 4; i++) {
    code += characters.charAt(Math.floor(Math.random() * characters.length))
  }
  weiCode = code
  // Draw background
  context.fillStyle = '#fff'
  context.fillRect(0, 0, canvas.width, canvas.height)

  // Draw random lines
  for (let i = 0; i < 10; i++) {
    context.beginPath()
    context.moveTo(Math.random() * canvas.width, Math.random() * canvas.height)
    context.lineTo(Math.random() * canvas.width, Math.random() * canvas.height)
    context.strokeStyle = '#333'
    context.stroke()
  }

  // Draw random dots
  for (let i = 0; i < 50; i++) {
    context.beginPath()
    context.arc(Math.random() * canvas.width, Math.random() * canvas.height, 1, 0, 2 * Math.PI)
    context.fillStyle = '#000'
    context.fill()
  }

  // Draw code
  context.font = '30px Arial'
  context.fillStyle = '#333'
  for (var i = 0; i < code.length; i++) {
    var x = 10 + i * 18
    var y = 30 + Math.random() * 10 - 5
    var angle = Math.random() * 0.4 - 0.2
    context.save()
    context.translate(x, y)
    context.rotate(angle)
    context.fillText(code.charAt(i), 0, 0)
    context.restore()
  }
  canvas.addEventListener('click', generateCaptcha)
}

// 加减法验证码
function generateSingleDigitCaptcha() {
  const canvas = document.getElementById('captchaCanvas') as HTMLCanvasElement
  const context = canvas.getContext('2d') as CanvasRenderingContext2D
  canvas.addEventListener('click', generateSingleDigitCaptcha)
  // Set canvas dimensions
  canvas.width = 100
  canvas.height = 40

  // Generate random operands and operator
  const operands = [
    Math.floor(Math.random() * 10),
    Math.floor(Math.random() * 10),
  ]
  // const operators = ['+', '-', '*', '/']
  const operators = ['+']
  const operator = operators[Math.floor(Math.random() * operators.length)]

  // Calculate answer
  let answer: number = operands[0] + operands[1]
  // switch (operator) {
  //   case '+':
  //     answer = operands[0] + operands[1]
  //     break
  //   case '-':
  //     answer = operands[0] - operands[1]
  //     break
  //   case '*':
  //     answer = operands[0] * operands[1]
  //     break
  //   case '/':
  //     answer = operands[0] / operands[1]
  //     break
  // }

  // Draw background
  context.fillStyle = '#00FFFF'
  context.fillRect(0, 0, canvas.width, canvas.height)

  // Draw operands and operator
  context.font = 'bold 30px Arial'
  context.fillStyle = '#000'
  context.fillText(
    `${operands[0]}${operator}${operands[1]} = ?`,
    Math.random() * 20,
    Math.random() * 45 + 15
  )

  // Draw random dots
  for (let i = 0; i < 50; i++) {
    context.beginPath()
    context.arc(
      Math.random() * canvas.width,
      Math.random() * canvas.height,
      1,
      0,
      2 * Math.PI
    )
    context.fillStyle = '#FFF'
    context.fill()
  }

  // Set global variable for captcha answer
  weiCode = answer.toString()
}

const isPhone = () => {
  const handler = isMobile()
  if (!handler) {
    showDialog({
      title: '温馨提示',
      message: '检查到当前用户设备为非移动端设备，为了您的体验建议使用手机等设备登录使用。',
    }).then(() => {
      // on close
    });
  }
}

onMounted(() => {
    isPhone()
    settings.handlerHeaderShow(false)
    settings.handlerFooterShow(false)
    // generateCaptcha()
    generateSingleDigitCaptcha()
    // play()
})

</script>


<style lang="scss" scoped>
.content {
    width: 100%;
    height: 100vh;
    position: relative;
    // background: linear-gradient(to bottom, #322357, #36265f, #48327d);
    background-image: url('@/assets/img/bg.jpg');
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
    overflow: hidden;
    padding: 15px;
    .line {
      width: 100%;
      height: 1px;
      background-color: #00FFFF;
    }
    padding: 0 20px;
    .usernameBox {
      margin-top: 100px;
      padding: 5px 15px;
      :deep(.van-cell) {
        background-color: transparent; // 透明背景
      }
      :deep(.van-field__control) {
          padding-left: 30px; /* 左边的边距 */
          color: #00FFFF;
      }
      :deep(.van-field__control::placeholder) {
        padding-left: 10px; /* 左边的边距 */
        color: #00FFFF;
      }
    }
    .passwordBox {
      padding: 5px 15px;
      :deep(.van-cell) {
        background-color: transparent; // 透明背景
      }
      :deep(.van-field__control) {
        padding-left: 30px; /* 左边的边距 */
        color: #00FFFF;
      }
      :deep(.van-field__control::placeholder) {
        padding-left: 10px; /* 左边的边距 */
        color: #00FFFF;
      }
    }
    .captchaBox {
      margin-top: 10px;
      padding: 5px 15px;
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: center;
      :deep(.van-cell) {
        background-color: transparent; // 透明背景
      }
      :deep(.van-field__control) {
        padding-left: 30px; /* 左边的边距 */
        color: #00FFFF;
      }
      :deep(.van-field__control::placeholder) {
        padding-left: 10px; /* 左边的边距 */
        color: #00FFFF;
      }
      :deep(.van-cell van-cell--borderless van-field) {
        width: 100%;
      }
    }
    .login-btn {
      position: absolute;
      left: 50%;
      transform: translateX(-50%);
      margin-top: 30px;
      width: 85%;
      height: 50px;
      border-radius: 16px;
      border: none;
      // background-color: #bca1f3;
      background-color: #00FFFF;
      font-size: 16px;
      font-weight: 500;
      color: #000;
    }
    /* 定义淡入动画 */
    @keyframes fadeIn {
      from {
        opacity: 0; /* 开始时完全透明 */
      }
      to {
        opacity: 1; /* 结束时完全不透明 */
      }
    }
    
    /* 应用动画到div元素 */
    .fade-in {
      animation-name: fadeIn; /* 指定动画名称 */
      animation-duration: 4.5s; /* 动画持续时间，这里是2秒 */
      animation-timing-function: ease; /* 动画速度曲线 */
      animation-fill-mode: forwards; /* 动画结束后保持最后一帧状态 */
    }
}
</style>